package logic

import (
	"context"
	"encoding/json"
	"furni-max/models/cache"
	"furni-max/models/mysql"
	"time"

	"furni-max/funcirpc/funcirpc"
	"furni-max/funcirpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type FuncListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewFuncListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *FuncListLogic {
	return &FuncListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *FuncListLogic) FuncList(in *funcirpc.FuncListRequest) (*funcirpc.FuncListResponse, error) {
	// todo: add your logic here and delete this line

	key := "tookList"
	var toolData []mysql.ToolData

	result, _ := cache.Rdb.Get(l.ctx, key).Result()

	if result == "" {
		mysql.DB.Debug().Model(&mysql.Tool{}).
			Select("tools.*,classes.name as class_name,brands.name as brand_name").
			Joins("LEFT JOIN classes ON tools.class_id = classes.id").
			Joins("LEFT JOIN brands on tools.brand_id = brands.id").
			Find(&toolData)

		marshal, _ := json.Marshal(toolData)

		cache.Rdb.Set(l.ctx, key, marshal, time.Hour*1)
	} else {
		json.Unmarshal([]byte(result), &toolData)
	}
	var toolLists []*funcirpc.ToolList

	for _, data := range toolData {
		list := funcirpc.ToolList{
			Name:      data.Name,
			Price:     float32(data.Price),
			Stock:     data.Stock,
			Image:     data.Image,
			Info:      data.Info,
			ClassName: data.ClassName,
			BrandName: data.BrandName,
			ToolId:    int64(data.ID),
		}
		toolLists = append(toolLists, &list)
	}

	return &funcirpc.FuncListResponse{
		List: toolLists,
	}, nil
}
